﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace work55
{


    //客户
    public class Client : Object
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public Client(int Id, string Name)
        {
            this.Id = Id;
            this.Name = Name;
        }

        public Client()
        {
        }

        public override string ToString()
        {
            return "ID为" + Id + "的" + Name;
        }

        public override bool Equals(Object obj)
        {
            Client Test = (Client)obj;
            if (this.Id == Test.Id && this.Name.Equals(Test.Name))
            {
                return true;
            }
            return false;
        }

    }

    //货物
    public class Goods : Object
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Price { get; set; }

        public Goods(int Id, string Name, int Price)
        {
            this.Id = Id;
            this.Name = Name;
            this.Price = Price;
        }

        public Goods()
        {
        }

        public override string ToString()
        {
            return "单价是：" + Price + " 的" + Name + " ";
        }

        public override bool Equals(Object obj)
        {
            Goods Test = (Goods)obj;
            if (this.Id == Test.Id && this.Name.Equals(Test.Name) && this.Price == Test.Price)
            {
                return true;
            }
            return false;
        }

    }

    //订单类
    public class Order
    {
        public int Id { get; set; }
        public DateTime buytime;       //购买时间
        public Client Client { get; set; } //客户
        public int Account { get; set; }   //订单总价
        public List<OrderDetail> OrderDetails; //订单明细

        public Order(int Id, Client Client, List<OrderDetail> OrderDetails)
        {
            this.Id = Id;
            buytime = DateTime.Now;
            //确认订单详情中不存在相同的商品
            foreach (OrderDetail orderDetail in OrderDetails)
            {
                for (int i = OrderDetails.IndexOf(orderDetail) + 1; i < OrderDetails.Count; i++)
                {
                    if (orderDetail.Equals(OrderDetails[i]))
                    {
                        orderDetail.GoodsNumber += OrderDetails[i].GoodsNumber;
                        OrderDetails.RemoveAt(i);
                    }
                }
                Account += orderDetail.GoodsNumber * orderDetail.Goods.Price;
            }
            this.OrderDetails = OrderDetails;
        }

        public override bool Equals(Object obj)
        {
            Order Test = (Order)obj;
            if (this.buytime.Equals(Test.buytime) && this.Id == Test.Id && this.Client.Equals(Test.Client) && this.OrderDetails.Equals(Test.OrderDetails) && this.Account == Test.Account)
                return true;
            return false;
        }

        public override string ToString()
        {
            return Client.ToString() + "在:" + buytime.ToString() + "购买了" + OrderDetails.ToString() + " 总价为:" + this.Account + " 订单号为：" + this.Id;
        }

    }

    //订单详情类
    public class OrderDetail
    {
        public int GoodsNumber { set; get; }   //货物数量
        public Goods Goods { get; set; }   //货物

        public OrderDetail(int GoodsNumber, Goods Goods)
        {
            this.GoodsNumber = GoodsNumber;
            this.Goods = Goods;
        }

        public OrderDetail()
        {
        }

        public override bool Equals(Object obj)
        {
            OrderDetail Test = (OrderDetail)obj;
            if (this.Goods.Equals(Test.Goods))
                return true;
            return false;
        }

        public override string ToString()
        {
            return Goods.ToString() + GoodsNumber + " 件";
        }

    }

    //自定义异常
    public class Attention : Exception
    {
        public Attention(string message) : base(message) { }
    }
    //异常处理层
    public class WriteAttention
    {
        public static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }

    //订单操作类
    public class OrderService
    {
        public static List<Order> Orders = new List<Order>();
        public static int OrderId = 0;

        //添加订单
        public static bool AddOrder(Client Client, List<OrderDetail> OrderDetails)
        {
            Order NewOrder = new Order(OrderId, Client, OrderDetails);
            foreach (Order order in Orders)
            {
                if (NewOrder.Equals(order))
                    return false;
            }
            OrderId++;
            Orders.Add(NewOrder);
            return true;
        }

        //删除订单
        public static bool DeleteOrder(int Id)
        {
            try
            {
                var query1 = from o in Orders
                             where o.Id == Id
                             select o;
                Order order = (Order)query1;
                if (query1.Equals(null))
                    throw new Attention("找不到该订单,无法删除");
                Orders.Remove(order);
                return true;
            }
            catch (Attention attention)
            {
                WriteAttention.Print(attention.Message);
                return false;
            }
        }

        //修改订单
        public static bool AlterOrder(int Id, Client Client, List<OrderDetail> OrderDetails)
        {
            try
            {
                var query1 = from o in Orders
                             where o.Id == Id
                             select o;
                Order order = (Order)query1;
                if (query1.Equals(null))
                    throw new Attention("找不到该订单，无法修改");
                Orders.Remove(order);
                order.Client = Client;
                order.OrderDetails = OrderDetails;
                return true;
            }
            catch (Attention attention)
            {
                WriteAttention.Print(attention.Message);
                return false;
            }
        }

        //查询订单
        //按照订单号
        public static Order FindOrderById(int Id)
        {
            try
            {
                var query1 = from o in Orders
                             where o.Id == Id
                             select o;
                Order order = (Order)query1;
                if (!query1.Equals(null))
                {
                    return order;
                }
                throw new Attention("找不到该订单，试试换一个ID");

            }
            catch (Attention attention)
            {
                WriteAttention.Print(attention.Message);
                return null;
            }
        }

        //按照商品名称
        public static List<Order> FindOrderByGoodsName(string name)
        {
            try
            {
                var query1 = Orders
                    .Where(o => o.OrderDetails.Exists(g => g.Goods.Name.Equals(name)))
                    .OrderBy(o => o.Account);
                List<Order> orders = query1.ToList();

                if (!query1.Equals(null))
                {
                    return orders;
                }
                throw new Attention("找不到该订单，试试换一个商品名");
            }
            catch (Attention attention)
            {
                WriteAttention.Print(attention.Message);
                return null;
            }
        }

        //按照客户姓名
        public static List<Order> FindOrderByClientName(string name)
        {
            try
            {
                var query1 = Orders
                    .Where(o => o.Client.Name.Equals(name))
                    .OrderBy(o => o.Account);
                List<Order> orders = query1.ToList();

                if (!query1.Equals(null))
                {
                    return orders;
                }
                throw new Attention("找不到该订单，试试换一个商品名");
            }
            catch (Attention attention)
            {
                WriteAttention.Print(attention.Message);
                return null;
            }
        }

        //按照订单金额
        public static List<Order> FindOrderByAccount(int account)
        {
            try
            {
                var query1 = Orders
                    .Where(o => o.Account == account)
                    .OrderBy(o => o.Account);
                List<Order> orders = query1.ToList();
                if (!query1.Equals(null))
                {
                    return orders;
                }
                throw new Attention("找不到该订单，试试换一个订单金额");
            }
            catch (Attention attention)
            {
                WriteAttention.Print(attention.Message);
                return null;
            }
        }


        //默认排序
        public static void Sort()
        {
            var query1 = Orders
                    .OrderBy(o => o.Id);
            List<Order> orders = query1.ToList();
            Orders = orders;
        }

        //lambda排序
        public static void SortByLambda(Action<Order, Order> LambdaExpression)
        {
            //根据lambda表达式进行冒泡排序
            foreach (Order order in Orders)
            {
                for (int i = Orders.IndexOf(order) + 1; i < Orders.Count; i++)
                {
                    LambdaExpression(order, Orders[i]);
                }
            }
        }

        //Export将订单转为xml文件
        public static void Export(string url)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Order>));
            using (FileStream f = new FileStream(url, FileMode.Create))
            {
                xmlSerializer.Serialize(f, Orders);
            }
        }

        //Import从XML文件中获取信息
        public static void Import(string url)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Order>));
            using (FileStream f = new FileStream(url, FileMode.Open))
            {
                Orders = (List<Order>)xmlSerializer.Deserialize(f);
            }
        }

    }

    //UI
    public class UI
    {
        //help
        public static void Help()
        {
            Console.WriteLine("ADDORDER: 新建订单");
            Console.WriteLine("DELETEORDER： 删除订单");
            Console.WriteLine("ALTERORDER： 修改订单");
            Console.WriteLine("SEARCHBYID： 根据订单ID查询订单");
            Console.WriteLine("SEARCHBYGOODS： 根据商品名查询订单");
            Console.WriteLine("SEARCHBYCLIENT： 根据购买者查询订单");
            Console.WriteLine("SEARCHBYACCOUNT： 根据订单金额查询订单");
            Console.WriteLine("HELP： 帮助");
            Console.WriteLine("ESC： 结束运行");
        }

        //单行输出
        public static void Attention(string s)
        {
            Console.WriteLine(s);
        }

        //订单列表输出
        public static void Attentions(List<Order> os)
        {
            foreach (Order o in os)
            {
                Console.WriteLine(o.ToString());
            }
        }

        //获取命令输入
        public static string GetIn()
        {
            return Console.ReadLine(); ;
        }

        //创建订单输入
        public static int[] GetAddIn()
        {
            int MAXSIZE = 100;
            int[] a = new int[MAXSIZE];
            string[] s = { "请输入购买客户的ID：", "请输入购买商品的ID", "请输入购买商品的数量", "确认创建？(Y/N)" };
            for (int i = 0; i < MAXSIZE; i++)
            {
                Console.WriteLine(s[i % 4]);
                if (i % 4 == 3)
                {
                    switch (Console.ReadLine())
                    {
                        case "Y":
                            a[i] = -1;  //创建订单
                            return a;
                        case "N":
                            a[i] = -2;  //继续输入
                            break;
                    }
                }
                else
                {
                    a[i] = Console.Read();
                }
            }
            return a;
        }

        //获取订单号输入
        public static int GetOrderId()
        {
            return Console.Read();
        }

        //修改订单输入
        public static int[] GetAlterIn()
        {
            int MAXSIZE = 100;
            int[] a = new int[MAXSIZE];
            string[] s = { "请输入订单的ID：", "请输入购买客户的ID：", "请输入购买商品的ID", "请输入购买商品的数量", "确认修改？(Y/N)" };
            for (int i = 0; i < MAXSIZE; i++)
            {
                Console.WriteLine(s[i % 5]);
                if (i % 5 == 4)
                {
                    switch (Console.ReadLine())
                    {
                        case "Y":
                            a[i] = -1;  //创建订单
                            return a;
                        case "N":
                            a[i] = -2;  //继续输入
                            break;
                    }
                }
                else
                {
                    a[i] = Console.Read();
                }
            }
            return a;
        }

        public static void ShowGoods(List<Goods> GoodsList)
        {
            Console.WriteLine("可购买的商品有：");
            GoodsList.ForEach(g => Console.WriteLine(g.ToString()));
            Console.WriteLine("**********8***************");
        }

        public static void ShowClients(List<Client> Clients)
        {
            Console.WriteLine("已注册的用户有：");
            Clients.ForEach(g => Console.WriteLine(g.ToString()));
            Console.WriteLine("**********8***************");
        }

        public static void ShowOrders(List<Order> Orders)
        {
            Console.WriteLine("*********所有订单*********");
            Orders.ForEach(g => Console.WriteLine(g.ToString()));
            Console.WriteLine("**********8***************");
        }

    }


    class Program
    {
        static List<Client> Clients = new List<Client>();
        static List<Goods> GoodsList = new List<Goods>();

        static void Main(string[] args)
        {
            //新建商品和用户
            for (int i = 1; i <= 5; i++)
            {
                Client client = new Client(i, "用户" + i);
                Goods goods = new Goods(i, "商品" + i, i * 10);
                Clients.Add(client);
                GoodsList.Add(goods);
            }
            //新建订单详情然后创建订单
            Clients.ForEach(c =>
            {
                List<OrderDetail> orderDetails = new List<OrderDetail>();
                GoodsList.ForEach(g =>
                {
                    OrderDetail o = new OrderDetail(1, g);
                    orderDetails.Add(o);
                });
                OrderService.AddOrder(c, orderDetails); //创建订单
            });

            while (true)
            {
                UI.Help();
                UI.Attention("请输入命令：");
                string order;
                order = UI.GetIn();
                switch (order)
                {
                    case "ADDORDER":
                        //显示商品列表和用户信息
                        UI.ShowGoods(GoodsList);
                        UI.ShowClients(Clients);
                        //选择信息创建订单
                        List<OrderDetail> OrderDetails = new List<OrderDetail>();
                        int[] c1d = UI.GetAddIn();
                        for (int i = 0; i < c1d.Length; i++)
                        {
                            Client client = new Client();
                            Goods goods = new Goods();
                            OrderDetail orderDetail = new OrderDetail();
                            switch (i % 4)
                            {
                                case 0:
                                    var var1 = Clients
                                        .Select(c => c.Id == c1d[i]);
                                    client = (Client)var1;
                                    break;
                                case 1:
                                    var var2 = GoodsList
                                         .Select(c => c.Id == c1d[i]);
                                    goods = (Goods)var2;
                                    break;
                                case 2:
                                    orderDetail = new OrderDetail(c1d[i], goods);
                                    break;
                                case 3:
                                    if (c1d[i] == -2)
                                        OrderDetails.Add(orderDetail);
                                    else
                                    {
                                        OrderService.AddOrder(client, OrderDetails);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "DELETEORDER":
                        int id = UI.GetOrderId();
                        OrderService.DeleteOrder(id);
                        break;
                    case "ALTERORDER":
                        UI.ShowOrders(OrderService.Orders);
                        //选择信息修改订单
                        //未写
                        break;
                    case "SEARCHBYID":
                        UI.Attention(OrderService.FindOrderById(UI.GetOrderId()).ToString());
                        break;
                    case "SEARCHBYGOODS":
                        UI.Attentions(OrderService.FindOrderByGoodsName(UI.GetIn()));
                        break;
                    case "SEARCHBYCLIENT":
                        UI.Attentions(OrderService.FindOrderByClientName(UI.GetIn()));
                        break;
                    case "SEARCHBYACCOUNT":
                        UI.Attentions(OrderService.FindOrderByAccount(UI.GetOrderId()));
                        break;
                    case "HELP":
                        UI.Help();
                        break;
                    case "ESC":
                        return;
                }
            }
        }
    }

}
